<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat SSE Demo</title>
</head>
<body>

<h1>Server-Sent Events with POST</h1>

<div id="messages"></div>

<script>
    function startSSE() {
        const url = 'http://localhost:8088/ai/flux-demo'; // 后端服务器的完整 URL
        const name = 'John Doe'; // 假设前端需要传递一个 name 参数

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'text/event-stream'
            },
            body: new URLSearchParams({
                'name': name
            })
        }).then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = ''; // 用于缓存不完整的数据

            return new ReadableStream({
                start(controller) {
                    function read() {
                        reader.read().then(({ done, value }) => {
                            if (done) {
                                controller.close();
                                return;
                            }

                            buffer += decoder.decode(value, { stream: true });

                            // 检查是否有完整的事件块（每个事件块之间有两个换行符）
                            const eventBlocks = buffer.split("\n\n");

                            // 将最后一个块留在缓存里，可能是不完整的
                            buffer = eventBlocks.pop();

                            console.log("Parsed Event eventBlocks:", eventBlocks); // Debug: 查看解析后的完整数据

                            eventBlocks.forEach(eventBlock => {
                                const lines = eventBlock.split("\n");
                                let eventData = {};

                                lines.forEach(line => {
                                    if (line.startsWith("data:")) {
                                        eventData.data = line.substring(5); // 提取 "data: " 后的内容
                                    }
                                });

                                if (eventData.data) {
                                    displayMessage(eventData.data); // 显示消息
                                }

                                // console.log("Parsed Event Data:", eventData); // Debug: 查看解析后的完整数据
                            });

                            read();
                        });
                    }

                    read();
                }
            });
        }).catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });

    }

    function displayMessage(message) {
        const messageDiv = document.getElementById('messages');
        const newMessage = document.createElement('p');
        newMessage.textContent = message;
        messageDiv.appendChild(newMessage);
    }

    // 开始 SSE 连接
    startSSE();
</script>

</body>
</html>
